package cn.aylog.oss.utils;

import cn.aylog.oss.config.OssConfig;
import cn.hutool.core.lang.Snowflake;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class OssUtils {

    @Resource
    private OssConfig config;

    // 雪花算法生成器
    private Snowflake snowflake = new Snowflake();

    public String upload2Oss(InputStream is, String fileName) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(new Date());

        // 路径生成
        String dirPath = "test/" + dateStr + "/" + snowflake.nextIdStr();

        // 创建oss实例，与oss建立连接
        OSS ossClient = new OSSClientBuilder().build(
                config.getEndpoint(),
                config.getAccessKeyId(),
                config.getAccessKeySecret());

        // 文件上传
        ossClient.putObject(config.getBucketName(), dirPath + "/" + fileName,is);

        // 关闭实例
        ossClient.shutdown();

        // 返回上传的路径
        return config.getBaseUrl() + "/" + dirPath +"/" + fileName;
    }
}
